package org.neuedu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.neuedu.entity.DrugInfo;
import org.neuedu.entity.Prescription;
import org.neuedu.entity.Register;
import org.neuedu.mapper.PrescriptionMapper;
import org.neuedu.service.DrugInfoService;
import org.neuedu.service.PrescriptionService;
import org.neuedu.service.RegisterService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzw
 * @since 2024-11-19
 */
@Service
public class PrescriptionServiceImpl extends ServiceImpl<PrescriptionMapper, Prescription> implements PrescriptionService {
    @Resource
    RegisterService registerService;
    @Resource
    DrugInfoService drugInfoService;
    @Override
    public boolean add(String content) {
        List<Prescription> list = JSONObject.parseArray(content, Prescription.class);
        return this.saveBatch(list);
    }
    @Override
    public List<Prescription> jiaofei(String caseNumber, String drugState) {
        Register register = registerService.getByCaseNumber(caseNumber);
        List<Prescription> list = this.getByRegisterId(register.getId(), drugState);
        list.forEach(entry -> {
            entry.setDrugInfo(drugInfoService.getById(entry.getDrugId()));
        });
        return list;
    }

    @Override
    public boolean updateState(Integer[] ids) {
        UpdateWrapper<Prescription> wrapper = new UpdateWrapper<>();
        wrapper.in("id", ids);
        Prescription prescription = new Prescription();
        prescription.setDrugState("已缴费");
        return this.update(prescription, wrapper);
    }

    @Override
    public List<Prescription> fayao(String caseNumber) {
        return this.jiaofei(caseNumber, "已缴费");
    }

    @Override
    public String update(Integer id,Integer drugId,Integer drugNumber) {
        DrugInfo drugInfo= drugInfoService.getById(drugId);
        long quantity=drugInfo.getQuantity()-drugNumber;
        if ((drugInfo.getQuantity()-drugNumber)>=0){
            drugInfo.setQuantity(quantity);
            Prescription prescription = new Prescription(id, "已发药");
            this.updateById(prescription);
            return "开药成功";
        }else{
            return "开药失败，药品余量"+drugInfo.getQuantity();
        }

    }

    @Override
    public Boolean backMedical(Integer id) {
        return this.updateById(new Prescription(id,"已退药"));
    }

    private List<Prescription> getByRegisterId(Integer registerId, String drugState) {
        QueryWrapper<Prescription> wrapper = new QueryWrapper<>();
        wrapper.eq("register_id", registerId)
                .eq("drug_state", drugState);
        return this.list(wrapper);
    }
}
